package com.beerandjesus.photogallery.page;

import com.beerandjesus.photogallery.PhotoGalleryException;
import com.beerandjesus.photogallery.image.PhotoGalleryImage;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class PhotoGalleryPageImpl implements PhotoGalleryPage {

    private List<PhotoGalleryImage> list;
    private int numPerPage;

    private ListPagingStrategy pagingStrategy;
    private int page;
    private int index;
    private String title;
    private String description;
    private int lastPage;
    private int lastIndex;

    protected PhotoGalleryPageImpl(HttpServletRequest request, List<PhotoGalleryImage> list, ListPagingStrategy pagingStrategy, int numPerPage) throws PhotoGalleryException {
        this.list = list;
        this.pagingStrategy = pagingStrategy;
        this.numPerPage = numPerPage;
        String pageNum = request.getParameter("p");
        if (pageNum != null) {
            try {
                page = Integer.parseInt(pageNum);
            } catch (NumberFormatException e) {
                throw new PhotoGalleryException("Request parameter 'p' must be an integer", e);
            }
        } else {
            page = 1;
        }
        initIndex();
        initLastIndex();
        initLastPage();
    }

    private void initLastIndex() {
        lastIndex = pagingStrategy.endIndex(page, numPerPage, size());
    }

    private void initLastPage() {
        lastPage = pagingStrategy.lastPage(numPerPage, size());
    }

    private void initIndex() {
        index = pagingStrategy.startIndex(page, numPerPage, size());
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDescription() {
        return description;
    }

    public boolean hasNext() {
        return index <= lastIndex;
    }

    public PhotoGalleryImage next() {
        if (!hasNext()) {
            return null;
        }
        return list.get(index++);
    }

    public int size() {
        return list.size();
    }

    public int currentPage() {
        return page;
    }

    public int lastPage() {
        return lastPage;
    }
}
